﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OmronLib.Base;

namespace OmronLib
{
    public class FinsCommand : OmronBase
    {
        // CIO0.15    CIO10
        // IR10
        // DR10
        // TK10
        // D100       D10.15
        // H0.5       H10
        // W0.5       W10
        // A0.5       A10
        protected FinsParameter GetAddress(string variable)
        {
            Area area = Area.CIO;
            ushort wordAddr = 0;
            byte bitAddr = 0;
            DataType dataType = DataType.BIT;

            string charHead = variable.Substring(0, 3).ToUpper();
            if ("CIO".Equals(charHead))
            {
                dataType = DataType.WORD;
                string[] arr = variable.Substring(3).Split('.');
                wordAddr = ushort.Parse(arr[0]);
                if (arr.Length == 2)
                {
                    dataType = DataType.BIT;
                    bitAddr = byte.Parse(arr[1]);
                }
            }
            else if ("IRDRTK".Contains(variable.Substring(0,2).ToUpper()))
            {
                string head = variable.Substring(0,2).ToUpper();
                string str_addr = variable.Substring(2).ToUpper();
                area = Enum.Parse<Area>(head);
                wordAddr = ushort.Parse(str_addr);
            }
            else if ("DHWA".Contains(variable.Substring(0, 1).ToUpper()))
            {
                string head = variable.Substring(1).ToUpper();
                if (head == "D")
                    head += "M";
                else
                    head += "R";
                dataType = DataType.WORD;
                area = Enum.Parse<Area>(head);
                string[] str_arr = variable.Substring(1).Split('.');
                wordAddr = ushort.Parse(str_arr[0]);
                if(str_arr.Length == 2)
                {
                    dataType = DataType.BIT;
                    bitAddr = byte.Parse(str_arr[1]);
                }
            }

            return new FinsParameter()
            {
                Area = area,
                WordAddr = wordAddr,
                DataType = dataType,
                BitAddr = bitAddr
            };
        }
    }
}
